package com.test.platform.service.publish;

import com.test.platform.service.common.GitCodeApiClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.concurrent.CompletableFuture;

import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import com.test.platform.service.common.RepoConfigService;

@Service
public class GitCodeCommitService {
    private static final Logger logger = LoggerFactory.getLogger(GitCodeCommitService.class);

    @Autowired
    private GitCodeApiClient gitCodeApiClient;
    
    @Autowired
    private PublishDataProcessor dataProcessor;

    @Autowired
    private RepoConfigService repoConfigService;

    @Value("${publish.info.update.enabled}")
    private boolean updateEnabled;

    // 删除 @Scheduled 注解和 scheduledUpdateCommits 方法
    
    public CompletableFuture<Boolean> updateCommitInfo(String owner, String name, String version) {
        if (!updateEnabled) {
            logger.info("提交信息更新功能已禁用，跳过更新: {}/{}", owner, name);
            return CompletableFuture.completedFuture(false);
        }

        try {
            JsonNode prInfo = gitCodeApiClient.fetchLatestPR(owner, name);
            String commitSha = null;
            
            if (prInfo != null) {
                if (prInfo.isArray() && prInfo.size() > 0) {
                    commitSha = prInfo.get(0).path("head").path("sha").asText();
                } else if (prInfo.isObject()) {
                    Map.Entry<String, JsonNode> entry = prInfo.fields().next();
                    if (entry != null && entry.getValue().has("sha")) {
                        commitSha = entry.getValue().get("sha").asText();
                    }
                }
            }
            
            // 获取 changelog 信息
            Map<String, String> changelogInfo = gitCodeApiClient.fetchChangelog(owner, name, null);
            String changelog = changelogInfo.get("changelog");
            // 如果获取到新的版本号，使用新的版本号
            version = changelogInfo.getOrDefault("version", version);
            
            if (commitSha != null && !commitSha.isEmpty()) {
                return dataProcessor.processCommitInfo(owner, name, version, commitSha, changelog);
            } else {
                logger.warn("未获取到提交SHA: {}/{}", owner, name);
                return CompletableFuture.completedFuture(false);
            }
        } catch (Exception e) {
            logger.error("更新提交信息时发生错误: {}/{}", owner, name, e);
            return CompletableFuture.completedFuture(false);
        }
    }

    public void updateAllReposCommitInfo() {
        try {
            List<Map<String, String>> repos = repoConfigService.loadRepoConfigs();
            logger.info("开始更新所有仓库的提交信息，共 {} 个仓库", repos.size());

            List<CompletableFuture<Boolean>> futures = new ArrayList<>();
            for (Map<String, String> repo : repos) {
                String owner = repo.get("owner");
                String name = repo.get("name");
                String version = repo.get("version");
                futures.add(updateCommitInfo(owner, name, version));
            }

            // 等待所有更新完成
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
            logger.info("所有仓库的提交信息更新完成");
        } catch (Exception e) {
            logger.error("批量更新仓库提交信息时发生错误", e);
            throw new RuntimeException("更新提交信息失败", e);
        }
    }
}